<template>
  <div class="vc-page">
    <!-- 查询条件 -->
    <query-terms ref="queryTerms" :searchConfig="searchConfig" />

    <!-- 操作按钮 -->
    <el-row class="vc-btns">
      <el-button type="primary" size="small" @click="addDialogVisible = true"
        >新增</el-button
      >
      <el-button
        size="small"
        :disabled="selectedIds.length === 0"
        @click="batchDel"
        >删除</el-button
      >
    </el-row>

    <!-- 列表展示 -->
    <div class="vc-table">
      <tables
        v-model="tableConfig.tableData"
        :columns="tableConfig.columns"
        :stripe="true"
        @on-selection-change="handleSelectionChange"
      />

      <el-pagination
        :current-page="currentPage"
        @current-change="handleCurrentChange"
        :page-size="GLOBAL.QUERY.PAGE_SIZE"
        :total="total"
        layout="total, prev, pager, next"
      >
      </el-pagination>
    </div>
    <!-- 新增 -->
    <add-user
      :dialogVisible="addDialogVisible"
      @close="closeAddDialog"
    ></add-user>

    <!-- 修改 -->
    <edit-user
      :entity="entity"
      :dialogVisible="editDialogVisible"
      @close="closeEditDialog"
    ></edit-user>

    <!-- 重置密码 -->
    <reset-pwd
      :entity="entity"
      :dialogVisible="resetPwdDialogVisible"
      @close="closeResetPwdDialog"
    ></reset-pwd>
  </div>
</template>

<script>
import AddUser from './add'
import EditUser from './edit'
import ResetPwd from './resetPwd'
const defaultForm = {
  status: 'draft',
  title: '', // 文章题目
  content: '', // 文章内容
  content_short: '', // 文章摘要
  source_uri: '', // 文章外链
  image_uri: '', // 文章图片
  display_time: undefined, // 前台展示时间
  id: undefined,
  platforms: ['a-platform'],
  comment_disabled: false,
  importance: 0
}
export default {
  name: 'user',
  components: { AddUser, EditUser, ResetPwd },
  data () {
    return {
      // 查询条件
      postForm: Object.assign({}, defaultForm),
      searchConfig: {
        items: [
          {
            key: 'username',
            title: '用户名'
          },
          {
            key: 'nickname',
            title: '昵称'
          },
          {
            key: 'type',
            title: '用户类型',
            type: 'select',
            placeholder: '请选择',
            groups: this.$store.state.dic.listFormat['yhlx']
          },
          {
            key: 'state',
            title: '用户状态',
            type: 'select',
            placeholder: '请选择',
            groups: this.$store.state.dic.listFormat['yhzt']
          },
          {
            key: 'nature',
            title: '用户性质',
            type: 'select',
            placeholder: '请选择',
            groups: this.$store.state.dic.listFormat['yhxz']
          },
          {
            key: 'invalidTime',
            title: '失效时间',
            type: 'daterange',
            startPlaceholder: '请选择',
            endPlaceholder: '请选择'
          }
        ],
        search: params => {
          this.search(params)
        },
        reset: () => {
          this.reset()
        },
        params: {}
      },
      searchData: {
        username: '',
        nickname: '',
        type: '',
        state: '',
        nature: '',
        invalidTime: ''
      },
      // 列表
      tableConfig: {
        columns: [
          {
            type: 'selection'
          },
          {
            type: 'index'
          },
          {
            title: '用户名',
            key: 'username'
          },
          {
            title: '昵称',
            key: 'nickname'
          },
          {
            title: '用户类型',
            key: 'type',
            formatType: row => this.GLOBAL.formatter.formatTableCol(row.type, 'yhlx')
          },
          {
            title: '用户状态',
            key: 'state',
            formatType: row => this.GLOBAL.formatter.formatTableCol(row.state, 'yhzt')
          },
          {
            title: '用户性质',
            key: 'nature',
            formatType: row => this.GLOBAL.formatter.formatTableCol(row.nature, 'yhxz')
          },
          {
            title: '失效时间',
            key: 'invalidTime',
            width: '170px',
            formatType: row => this.GLOBAL.formatter.formatDateTime(row.invalidTime, 'YYYY-MM-DD hh:mm:ss')
          },
          {
            type: 'option',
            minWidth: '88',
            items: [
              {
                title: '修改',
                class: 'edit',
                click: row => {
                  this.handleEdit(row)
                }
              },
              {
                title: '重置密码',
                icon: 'vc-icon vc-icon-table-resetPwd',
                click: row => {
                  this.handleResetPwd(row)
                }
              },
              {
                title: '激活',
                icon: 'vc-icon vc-icon-table-delay',
                isShow: row => {
                  return row.state === this.GLOBAL.CONSTANTS.USER_STATE_SLEEP || row.nature === this.GLOBAL.CONSTANTS.DEFAULT_USER_NATURE
                },
                click: row => {
                  this.confirm(row, 'activeUser', '确定激活该用户吗？', '激活')
                }
              },
              {
                title: '解锁',
                icon: 'vc-icon vc-icon-table-unlock',
                isShow: row => {
                  return row.state === this.GLOBAL.CONSTANTS.USER_STATE_LOCK
                },
                click: row => {
                  this.confirm(row, 'unlockUser', '确定解锁该用户吗？', '解锁')
                }
              }
            ]
          }
        ],
        tableData: []
      },
      currentPage: 1,
      total: 0,
      selectedIds: [],
      entity: {},
      addDialogVisible: false,
      editDialogVisible: false,
      resetPwdDialogVisible: false
    }
  },
  created () {
  },
  methods: {
    /**
     * 加载列表数据
     */
    getUsersByPage (pageNum = this.currentPage, pageSize = this.GLOBAL.QUERY.PAGE_SIZE, entity = this.searchData) {
      this.$api.getUsersByPage({
        data: {
          pageNum: pageNum,
          pageSize: pageSize,
          params: entity
        }
      }).then(res => {
        if (!res.success || !res.data.total) {
          this.emptyTableData()
          return
        }
        if (!res.data.records || !res.data.records.length) {
          this.currentPage--
          this.getUsersByPage()
          return
        }
        this.tableConfig.tableData = res.data.records
        this.total = res.data.total
        this.currentPage = res.data.current
      }).catch(() => {
        this.emptyTableData()
      })
    },
    /**
     * 清空表格数据
     */
    emptyTableData () {
      this.tableConfig.tableData = []
      this.total = 0
      this.currentPage = 1
    },
    /**
     * 点击页数
     */
    handleCurrentChange (val) {
      this.getUsersByPage(val)
    },
    /**
     * 查询
     */
    search (params) {
      let list = params.invalidTime || []
      this.searchData = Object.assign(list.length ? {
        startInvalidTime: list[0],
        endInvalidTime: list[1] + 86399000
      } : {}, this.GLOBAL.filter.filterSpace(params), { invalidTime: '' })
      this.currentPage = 1
      this.getUsersByPage()
    },
    /**
     * 重置
     */
    reset () {
      this.search(this.GLOBAL.object.clearValOfObj(this.searchData))
    },
    /**
     * '新增'弹出框关闭事件
     */
    closeAddDialog (val) {
      this.addDialogVisible = false
      val && this.$refs.queryTerms.reset()
    },
    /**
     * 复选框勾选
     */
    handleSelectionChange (val) {
      this.selectedIds = this.GLOBAL.array.selectOneKey(val, 'id')
    },
    /**
     * '删除'按钮点击事件
     */
    batchDel () {
      this.$confirmBox(this.handleDel)
    },
    /**
     * 删除
     */
    handleDel () {
      this.$api.deleteUsersByIds({
        data: this.selectedIds
      }).then(res => {
        this.getUsersByPage()
        res.success && this.$notifyBox('删除成功', 'success')
      })
    },
    /**
     * 操作列-修改
     */
    handleEdit (row) {
      this.entity = Object.assign({}, row)
      this.editDialogVisible = true
    },
    /**
     * '修改'弹出框关闭事件
     */
    closeEditDialog (val) {
      this.editDialogVisible = false
      if (!val) return
      this.getUsersByPage()
      val.id === this.$store.state.user.userInfo.userId && this.$store.dispatch('getUserInfo')
    },
    /**
     * 操作列-重置密码
     */
    handleResetPwd (row) {
      this.entity = Object.assign({}, row)
      this.resetPwdDialogVisible = true
    },
    /**
     * '重置密码'弹出框关闭事件
     */
    closeResetPwdDialog (val) {
      this.resetPwdDialogVisible = false
      val && this.getUsersByPage()
    },
    /**
     * 操作列-弹框确认
     */
    confirm (row, api, msg, name) {
      this.$confirmBox(() => {
        this.handleEvt(row, api, name)
      }, msg)
    },
    /**
     * 操作
     */
    handleEvt (row, api, name) {
      this.$api[api]({
        data: {
          id: row.id
        }
      }).then(res => {
        this.getUsersByPage()
        res.success && this.$notifyBox(`${name}成功`, 'success')
      })
    }
  }
}
</script>
